package com.ls.herostory.cmdhandler;

import com.ls.herostory.channel.handler.BroadCast;
import com.ls.herostory.mq.AttkMsg;
import com.ls.herostory.mq.MqProducer;
import com.ls.herostory.msg.GameMsgProtocol;
import com.ls.herostory.session.Session;
import com.ls.herostory.session.SessionUtil;
import com.ls.herostory.thread.AsyncOperationProcessor;
import com.sun.javafx.runtime.async.AsyncOperation;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author liangsu
 * @version v1.0
 * @Description
 * @Date 2020/10/12 16:57
 * @since
 */
public class UserAttkCmdHandler implements CmdHandler<GameMsgProtocol.UserAttkCmd>{

    @Override
    public void handleCmd(ChannelHandlerContext ctx, GameMsgProtocol.UserAttkCmd cmd) {
        System.out.println("exec thread: " + Thread.currentThread().getName());
        Session session = SessionUtil.getSession((NioSocketChannel) ctx.channel());
        if(session == null){
            return;
        }

        Session targetUserSession = SessionUtil.getSession(cmd.getTargetUserId());
        if(targetUserSession == null){
            // 没有攻击对象，广播攻击动作
            GameMsgProtocol.UserAttkResult userAttkResult = GameMsgProtocol.UserAttkResult.newBuilder()
                    .setAttkUserId(session.getUserId())
                    .setTargetUserId(-1)
                    .build();
            BroadCast.cast(userAttkResult);
            return;
        }

        int speed = 10;
        targetUserSession.setHp(targetUserSession.getHp() - speed);

        // 攻击消息
        GameMsgProtocol.UserAttkResult userAttkResult = GameMsgProtocol.UserAttkResult.newBuilder()
                .setAttkUserId(session.getUserId())
                .setTargetUserId(cmd.getTargetUserId())
                .build();
        BroadCast.cast(userAttkResult);

        // 减血消息
        GameMsgProtocol.UserSubtractHpResult userSubtractHpResult = GameMsgProtocol.UserSubtractHpResult.newBuilder()
                .setTargetUserId(cmd.getTargetUserId())
                .setSubtractHp(speed)
                .build();
        BroadCast.cast(userSubtractHpResult);

        // 死亡消息
        if(targetUserSession.getHp() <= 0){
            GameMsgProtocol.UserDieResult userDieResult = GameMsgProtocol.UserDieResult.newBuilder()
                    .setTargetUserId(cmd.getTargetUserId())
                    .build();
            BroadCast.cast(userDieResult);

            // 发送mq消息
            AttkMsg msg = new AttkMsg();
            msg.setUserId(session.getUserId());
            msg.setUserName(session.getUserName());
            msg.setHeroAvatar(session.getHeroAvatar());
            AsyncOperationProcessor.getIntance().process(() ->{
                MqProducer.getInstance().productAttkMsg(msg);
            });
        }

    }
}
